<template>
    <div class="wrapper">
		<!-- 遮罩层 -->
		<div class="layer" v-show="layerVisible">
			<div class="layer-tip">请等待下一题</div>
		</div>
		<!-- 遮罩层end -->
        <div class="banner">
              <div style="background-color: #d40c14;height: 100rpx"></div>
<!--            <img src="http://file.rzkeji.com/web/dang/question_banner.png">-->
        </div>
        <div class="content" v-if="contentFlag">
            <div class="title">
                <div class="tit">{{question_package_name}}</div>
            </div>
            <div class="answer_wrapper" v-show="flag">
                <button class="answer">准备开始...</button>
            </div>
            <div style="margin-top: 20px;width: 100%;text-align: center" v-show="isStartAnswer">
                <span style="font-size: 15px;color: white">{{msg}}</span>
                <span style="font-size: 20px;color: #ffd3b3;font-weight: bold">{{toNextTime}}</span>
            </div>
            <div class="answer_list" v-show="isStartAnswer">
                <ul >
                    <li :class="{active_selected: select_id == answer.id}"  v-for="(answer,index) in answerList" :key="index" @click="selectAnswer(answer.id)">{{answer.answer}}</li>
                </ul>
            </div>
        </div>
        <div class="content" v-if="!contentFlag">
            <div class="title">
                <div class="tit">
                    <div>你的成绩为：{{userFraction}}分</div>
                    <div>你的排名为:第{{userRank}}名</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

    //Socket心跳
    let heartCheck = {
        timeout: 5000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            this.timeoutObj = setInterval(()=> {
                console.log("发送ping");
                uni.sendSocketMessage({
                    data:"ping",
                });
            }, this.timeout);
        }
    };
    export default {
        name: "question",
        data(){
            return {
				layerVisible:false,//显示遮罩层
				user_token:'',
                contentFlag:true,
                websock:"",
                client_id:"",
                question_package_name:"正在准备题目",
                key:"",
                answerNow:false,
                delClientId:"",
                count:5,
                flag:true,
                answerList: [],
                isStartAnswer:false,
                toNextTime:15,
                readAnswerTime:3,
                allQuestionNum:0,
                theQuestionNum:0,
                qp_id: "",
                select_id:"",
                q_id:"",
                rightNum:"",
                msg:"答题倒计时：",
                sendAnswerFlag: true,
                userRank: '',
                userFraction: '',
                startTimeToNextFlag: true,
                timeoutObj: '',
            }
        },
        methods:{
            async getUserInfo(){
                let res=await this.$api.getSimpleUserInfo({
                  user_token:this.user_token
                });
                if(res.data.level == "success"){
                    console.log("success");
                }else {
                  if(res.data.data == 'no_login'){
                    uni.setStorageSync('history_url','/pages/answer/answer');
                    uni.redirectTo({
                      url:"/pages/index/index"
                    })
                  }else {
                    uni.showToast({
                      icon:'none',
                      title:res.data.message
                    })
                  }

                }
            },
            initWebSocket(){ //初始化weosocket
                const wsuri = `wss://api.rzkeji.com`
				        let This=this
                uni.connectSocket({
                	url: wsuri,
                	success() {
                		console.log('连接成功')
                		This.initEventHandle()
                	}
                });
            },
			initEventHandle(){
				var This = this;
				uni.onSocketMessage(function(res){
					This.websocketonmessage(res)
				});

				uni.onSocketOpen(function (res) {
                    heartCheck.reset().start();
					console.log('socket链接打开');
                    This.timeoutObj = setInterval(()=> {
                        console.log("发送ping");
                        uni.sendSocketMessage({
                            data:"ping",
                        });
                        // this.serverTimeoutObj = setTimeout(() =>{
                        // 	console.log("aaa")
                        // 	uni.closeSocket();
                        // }, this.timeout);
                    }, 5000);
				});
				uni.onSocketClose(function (res) {
                    heartCheck.reset();
					console.log('WebSocket断开！',);
                    clearTimeout(This.timeoutObj);
				});
				uni.onSocketError(function (res) {
					console.log('WebSocket连接错误！');
                    clearTimeout(This.timeoutObj);
					This.initWebSocket()
				});
			},
            websocketonmessage(e){
                console.log(e)
                let _this = this //数据接收
                var data=JSON.parse(e.data);
                var handle = data.handle || '';
                if(handle != "" && handle=="init"){
                    this.client_id=data.client_id
                    this.serverOnLine()
                }else if(handle != "" && handle=="start_answer"){
					this.layerVisible=false
                    this.flag = false
                    this.isStartAnswer = true
                    let theData = data.data
                    this.question_package_name = theData.question.question;
                    this.question_package_name = "题目"+(theData.current_num+1)+"："+ this.question_package_name + "("+theData.question.score+"分)"
					this.q_id = theData.question.id
                    this.answerList = theData.answers
                    this.toNextTime = 15
                    this.startTimeToNext((theData.current_num+1))
                }else if(handle!=='' && handle=='countdown'){
						if(data.data.current_num!=(this.theQuestionNum-1)){
							//服务端的题目与当前的题目不一致了
							this.layerVisible=true
							return
						}
					    this.toNextTime=data.data.remain;//获取倒计时的数字
					    if(this.toNextTime == 0){
					        this.sendAnswerFlag = false;
					        this.sendAnswer();
					        this.startTimeToNextFlag = true;
					        this.getAnswerResult()
					    }
				}
            },
            async serverOnLine(){
				let params={
					'client_id':this.client_id,
					"key":this.key,
					user_token:this.user_token
				}
                let res=await this.$api.clientOnline(params)
                if(res.data.level == "success"){
                    let data = res.data.data
                    this.qp_id = data.qp_id
                }else {
                    uni.showToast({
                    	icon:'none',
						title:res.data.message
                    })
					if(res.data.data=='finish'){
						//后台重进小程序，答题结束直接显示排行榜
						this.getUserRankAndFraction();
						this.contentFlag = false;
					}
                }
                this.getQuestionList();
            },
            async sendAnswer(){
				//发送答案
                if(this.select_id){
					let params={
						'q_id':this.q_id,
						"key":this.key,
						"aid":this.select_id,
						user_token:this.user_token
					}
                    let res=await this.$api.sendAnswer(params)
                    if(res.data.level == "success"){
                    }else{
                        uni.showToast({
                        	title:'none',
							title:res.data.message
                        })
                    }
                }
            },
            selectAnswer(id){
				//选题
                if(this.sendAnswerFlag){
                    this.select_id = id
                }
            },
            async getAnswerResult(){
				let params={
					'q_id':this.q_id,
					user_token:this.user_token
				}
                let res=await this.$api.getQuestionAnswers(params)
                if(res.data.level == "success"){
                    this.rightNum   = res.data.right_num
                    this.msg = "正确答案是："
                    this.toNextTime = this.rightNum
                }else {
                    uni.showToast({
                    	title:'none',
                    	title:res.data.message
                    })
                }
            },
            async getQuestionList(){
				//获取题目
				let params={
					'qp_id':this.qp_id,
					"key":this.key,
					user_token:this.user_token
				}

                let res=await this.$api.getQuestionsList(params)
                if(res.data.level == "success"){
                    let data = res.data.data
                    this.allQuestionNum = data.length
                }else {
                    uni.showToast({
                    	icon:'none',
						title:res.data.message
                    })
                }
            },
            startTimeToNext(current_num){
				//倒数进入下一题
                if(this.startTimeToNextFlag){
                    this.startTimeToNextFlag = false;
                }
                this.theQuestionNum=current_num;
                this.select_id = "";
                this.sendAnswerFlag = true;

                //扫码答题的以为二维码解析的线上版本的连接，需要把线上版本更新才能看到效果
                if(this.theQuestionNum == this.allQuestionNum){
                    setTimeout(()=>{
                        this.getUserRankAndFraction();
                    },18000)
                    setTimeout(()=>{
                        this.contentFlag = false
                    },21000)
                }
            },
            //答题完成后获取用户分数和排名
            async getUserRankAndFraction(){
				let params={
					"key":this.key,
					user_token:this.user_token
					}
                let res = await this.$api.getUserRankAndFraction(params)
                if(res.data.level == "success"){
                    let data = res.data.data;
                    this.userRank = data.rank;
                    this.userFraction = parseInt(data.answer_score).toString();
                }else {
                    uni.showToast({
                    	icon:'none',
                    	title:res.data.message
                    })
                }
            },
			getMeetingKey(){
				//获取会议key
				let ROUTER=getCurrentPages()
				let page=ROUTER[ROUTER.length-1]
				let options=page.options;
				options=decodeURIComponent(options.scene);
				let key=this.getQueryVariable('key',options);
				this.key=key;//会议key
        if(this.key && this.key != ''){
          uni.setStorageSync("q_key",this.key)
        }
				getApp().globalData.meetingKey=key;
			},
			getQueryVariable(variable,scene){
				var vars = scene.split("&");
				for (var i=0;i<vars.length;i++) {
					var pair = vars[i].split("=");
					if(pair[0] == variable){return pair[1];}
				}
				return(false);
			},
        },
        onShow(){
            console.log('onshow');
            this.user_token=uni.getStorageSync('userToken')
                  this.getMeetingKey();

            if(!this.key || this.key == ''){
               let qKey = uni.getStorageSync("q_key");
               if(qKey && qKey != ''){
                 this.key = qKey
               }
            }

            this.getUserInfo();
            this.initWebSocket();
        },
		onHide(){
			console.log('onHide')
			uni.closeSocket();
			this.client_id = '';
            clearTimeout(this.timeoutObj);
		},
		onUnload(){
			console.log('onUnLoad')
			uni.closeSocket();
			this.client_id = '';
            clearTimeout(this.timeoutObj);
		}
    }
</script>

<style scoped lang="scss">
	.layer{
		position: absolute;
		top:0;
		left:0;
		right: 0;
		bottom: 0;
		z-index: 10;
		background: rgba(0,0,0,0.6);
		color:#fff;
		font-weight: 800;
		font-size: 40rpx;
		.layer-tip{
			text-align: center;
			margin-top:300rpx;
		}
	}
    .wrapper{
        width:100%;
        height: 100vh;
		overflow-y: scroll;
        /*background: url('http://file.rzkeji.com/web/dang/small_backgroud.jpg');*/
        background-color: #d40c14;
		background-attachment: fixed;
    }

    .content{
        padding-top: 0.3rem;
    }

    .banner{
        width: 100%;
    }

    .banner img{
        width: 100%;
    }
    .active_selected{
        background-color: #ff9b54;
    }
    .title{
        margin: 0 auto;
        width: 75%;
        height: 100%;
        background: url("http://file.rzkeji.com/web/dang/q_name.png");
        background-size: 100% 100%;
    }

    .tit{
        text-align: center;
        padding:80rpx 40rpx;
        font-size: 28rpx;
        color:white;
    }

    .tit div{
        margin-top:14px;
    }

    .qrcode_wrapper{
        margin-top: 40px;
        width:100%;
        text-align: center;
    }
    .qrcode_wrapper p{
        margin-top: 10px;
        color: white;
    }
    .count{background-color: orange;border-radius: 50%;width: 200px;height: 200px;line-height: 200px;margin: 0 auto;margin-top: 30px;font-size: 100px;text-align: center;color: white}
    .question{
        font-size: 30px;
        text-align: center;
        margin-top:20px;
        width:calc(100% - 80px);
        margin-left:40px;
        background:#fff;
        border:1px solid #fff;
    }
    .answer_wrapper{
        width:100%;
        text-align: center;
        margin-top:40px;
    }
    .answer_wrapper button{
        background-color: orange;
        font-size: 24rpx;
        width: 200rpx;
        padding: 10rpx;
        border-radius: 10rpx;
        color: white;
        border: none;
    }
	.answer_list{
		ul{
			margin-top: 24rpx;color: white;
			li{
				margin: 20px auto;
				border: 2rpx solid orange;
				text-align: center;
				font-size: 28rpx;
				width: 70%;
				padding: 20rpx
			}
		}
	}
    /*.answer{*/
    /*font-size: 30px;*/
    /*font-weight: bold;*/
    /*width:200px;*/
    /*height: 80px;*/
    /*border-radius: 10px;*/
    /*}*/

    .man_item_list{
        display: flex;
        flex-wrap: wrap;
        margin-top:0.2rem;
        padding: 0 20px;
        color:#fff;
        font-size: 30px
    }
    .man_item{
        text-align: center;
        margin:10px;
    }
    .man_item div{
        width: 100%;
    }
    .man_item img{
        width:1.3rem;
        height: 1.3rem;
        object-fit:cover;
        border-radius: 50%;
    }

    .answering{
        color:#eee;
    }
</style>
